using System.Linq;
using System.Text;
using Framework.Core.Reflection;

namespace Framework.Core.Cache
{
    public class CacheKeyBuilder : ICacheKeyBuilder
    {
        private readonly IHashProvider hashProvider;

        public CacheKeyBuilder(IHashProvider hashProvider)
        {
            this.hashProvider = hashProvider;
        }

        public string Build(IMethod method)
        {
            const string separator = " ";
            var stringbuilder = new StringBuilder();

            stringbuilder.Append(method.Assembly);
            stringbuilder.Append(separator);
            stringbuilder.Append(method.Type);
            stringbuilder.Append(separator);
            stringbuilder.Append(method.Name);

            stringbuilder.Append("(");
            var arguments = method.Arguments.ToList();
            for (var i = 0; i < arguments.Count(); i++)
            {
                stringbuilder.Append(arguments[i].Type);
                stringbuilder.Append(separator);
                stringbuilder.Append(hashProvider.Create(arguments[i].Value));
                if (i < arguments.Count - 1)
                {
                    stringbuilder.Append(", ");
                }
            }
            stringbuilder.Append(")");

            return stringbuilder.ToString();
        }
    }
}